package org.testfire.realm.servlet;

/**
 * Created by IntelliJ IDEA.
 * User: granum
 * Date: Aug 20, 2007
 * Time: 10:35:27 AM
 */

import com.lookingglasssoftware.lgsrealm.LGSChecksum;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.testfire.realm.control.auth.user.UserDBAO;
import org.testfire.realm.control.exception.UpdateException;
import org.testfire.realm.control.exception.UserNotFoundException;
import org.testfire.realm.control.testfire.TestFireSubmitHandler;
import org.testfire.realm.model.entities.User;
import org.testfire.realm.model.entities.testfire.TestsetEntity;
import org.testfire.realm.util.S;
import org.testfire.realm.util.UtilityBean;

public class ExtensionPushServlet extends HttpServlet
{

    /**
     * {@inheritDoc
     */
    public void doPost(
        final HttpServletRequest request,
        final HttpServletResponse response )
        throws IOException, ServletException
    {
        doGet( request, response );
    }

    /**
     * {@inheritDoc
     */
    public void doGet(
        final HttpServletRequest request,
        final HttpServletResponse response )
        throws IOException, ServletException
    {
        Logger log = Logger.getLogger( this.getClass() );

        String userName = request.getParameter( "username" );
        String password = request.getParameter( "password" );
        User u = null;
        try
        {
            u = UserDBAO.getInstance().getUser( userName );
            String md5 = "";
            try
            {
                md5 = LGSChecksum.getHMAC_MD5( password, u.getName() + UtilityBean.SYSTEM_SALT );
            }
            catch ( Exception e )
            {
                log.error( "", e );
            }
            if ( !u.getMd5().equals( md5 ) )
            {
                throw new UserNotFoundException();
            }

        }
        catch ( UserNotFoundException e )
        {
            terminateIllegalRequest( response,
                "All Server Actions require valid username and password.\n" +
                    "'" + userName + "' is not a valid user or the password is invalid." );
        }

        if ( request.getRequestURI().endsWith( "addNewTestSet.do" ) )
        {

            String testsetXML = request.getParameter( "value" );

            if ( S.empty( testsetXML ) )
            {
                terminateIllegalRequest( response,
                    "Submission error.\n Testset is empty!" );
            }
            try
            {
                TestFireSubmitHandler h = new TestFireSubmitHandler( u, testsetXML );
                h.start();
                // yeah, well, that was pointless, as we have to wait for the parse to complete
                // so we can tell the submitter if it worked or not.
                while ( h.isAlive() )
                {
                    try
                    {
                        Thread.sleep( 50 );
                    }
                    catch ( InterruptedException e )
                    {/**/}
                }
                if ( h.getException() != null )
                {
                    throw (h.getException());
                }
                TestsetEntity testset = h.getTestsetEntity();
                if ( testset != null )
                {
                    PrintWriter out = response.getWriter();
                    out.write( testset.getTestsetdata() );
                    out.flush();
                }

            }
            catch ( UpdateException ex )
            {
                log.warn( "", ex );
                terminateIllegalRequest( response,
                    ex.getMessage() );
            }
            catch ( Exception ex )
            {
                log.warn( "", ex );
                terminateIllegalRequest( response,
                    ex.getMessage() );
            }

        }
    }

    /**
     * Terminate a session and send a 401 (Illegal Access) response.
     * <p/>
     * Generally we just tell the user nothing at all whatsever about why
     * their request was illegal.
     *
     * @param response The current Response.
     * @param message  The message to send, optionally null.
     * @throws IOException -
     */
    private void terminateIllegalRequest( HttpServletResponse response,
        String message ) throws IOException
    {
        PrintWriter out = response.getWriter();
        out.write( message );
    }

}

// eof: ExtensionPushServlet.java


